import { DataBus } from "../utils/DataBus";
import { Dialog } from "./Dialog";
import * as PIXI from 'pixi.js';
import * as UI from '@pixi/ui'
import { $t } from "../../plugins/i18n";
import { BaseNode } from "../nodes/com/BaseNode";
export class NodesSelector extends Dialog {

    constructor() {
        super('Select Node')
    }
    show(callBack?: (node: SelectBtnInfo) => void, option?: (SelectBtnInfo[]) | ((node: BaseNode) => boolean), caller?: BaseNode) {
        super.show()
        this.scrollBox.removeItems()
        if (typeof option === 'function' || option === undefined) {
            DataBus.allNodes.forEach(node => {
                if (((node.canReference && !option) || (option && option(node))) && (caller && caller.id != node.id)) {
                    const btn = this.getButton({
                        nodeId: node.id,
                        title: node.titleContent
                    }, callBack)
                    this.scrollBox.addItem(btn.view)

                }
            })
        } else {
            option.forEach(node => {
                if (caller?.id != node.nodeId) {
                    const btn = this.getButton(node, callBack)
                    this.scrollBox.addItem(btn.view)
                }
            })
        }
    }

    private getButton(node: SelectBtnInfo, callBack?: (node: SelectBtnInfo) => void) {
        const nodeBox = new PIXI.Container()
        const nodeBg = new PIXI.Graphics()
        const text = new PIXI.Text({
            text: $t(node.title),
            style: {
                fontSize: 16,
                fill: 0xffffff
            }
        })
        text.x = 5
        text.y = 5
        const rect = text.getLocalBounds()
        nodeBg.roundRect(1, 2, rect.width + 10, rect.height + 10, 5)
        nodeBg.fill({
            color: 0x1b2350
        })
        nodeBg.beginPath()
        nodeBg.roundRect(0, 0, rect.width + 10, rect.height + 10, 5)
        nodeBg.fill({
            color: 0x344395
        })

        nodeBox.addChild(nodeBg)
        nodeBox.addChild(text)
        const btn = new UI.Button(nodeBox)

        btn.onPress.connect(() => {
            callBack?.call(this, {
                nodeId: node.nodeId,
                title: node.title
            })
        })
        btn.onHover.connect(() => {
            nodeBg.alpha = 0.5
        })
        btn.onOut.connect(() => {
            nodeBg.alpha = 1
        })
        return btn
    }
}